section1_ui <- function(id) {
    page_fillable(
        # 第一板块
        layout_columns(
            height = "130px",
            card(
                fileInput(
                    inputId = NS(id, "infile"),
                    multiple = FALSE,
                    accept = c(
                        "text/csv",
                        "text/comma-separated-values,text/plain",
                        ".csv",
                        ".xlsx",
                        ".xls",
                        ".Rdata",
                        ".Rda"
                    ),
                    buttonLabel = "选择文件",
                    label = "上传需要分析的数据文件"
                ),
            ),
            card(
                card_header("行数"),
                textOutput(NS(id, "row_count"))
            ),
            card(
                card_header("列数"),
                textOutput(NS(id, "col_count"))
            ),
            col_widths = c(8, 2, 2)
        ),
        # 第二板块
        layout_columns(
            card(
                card_header("变量类型"),
                class = "vars-list",
                uiOutput((NS(id, "var_list"))),
            ),
            card(
                card_header("自定义变量类型"),
                selectInput(NS(id, "q_vars"), label = "选择要定义为数值的变量", choices = NULL, multiple = TRUE, selectize = T),
                selectInput(NS(id, "c_vars"), label = "选择要定义为因子的变量", choices = NULL, multiple = TRUE, selectize = T),
                actionButton(NS(id, "btn_update"), "更新类型", class = "btn-primary"),
                full_screen = TRUE,
                width = "100px",
            ),
            col_widths = c(9, 3),
        ),

        # 第三板块
        layout_column_wrap(
            card(
                card_header("缺失情况"),
                plotOutput(NS(id, "data_missing")),
                full_screen = TRUE,
                width = "100px"
            ),
            card(
                card_header("数据分布"),
                selectInput(
                    inputId = NS(id, "var_select"),
                    label = "选择变量",
                    choices = NULL
                ),
                uiOutput(NS(id, "data_summary")),
                plotlyOutput(NS(id, "data_dist")),
                full_screen = TRUE,
                width = "100px"
            )
        ),
        # 第四板块
        layout_column_wrap(
            width = "100px",
            card(
                card_header("数据预览"),
                dataTableOutput(NS(id, "data_preview")),
                full_screen = TRUE,
                width = "100px"
            )
        )
    )
}

sectionServer <- function(id) {
    moduleServer(id, function(input, output, session) {
        # 读取数据
        rv <- reactiveValues(data = NULL)
        observe({
            req(input$infile)
            ext <- tools::file_ext(input$infile$name)
            rv$data <- switch(ext,
                csv = read.csv(input$infile$datapath),
                xlsx = readxl::read_excel(input$infile$datapath),
                xls = readxl::read_excel(input$infile$datapath),
                rdata = get(load(input$infile$datapath)),
                rda = get(load(input$infile$datapath)),
                stop("Invalid file type")
            )
        })
        # 显示行数和列数
        output$row_count <- renderText({
            nrow(rv$data)
        })

        output$col_count <- renderText({
            ncol(rv$data)
        })

        # 显示变量列表
        get_quan_names <- reactive({
            names(rv$data)[sapply(rv$data, function(x) is.numeric(x))]
        })
        get_cat_names <- reactive({
            names(rv$data)[sapply(rv$data, function(x) is.factor(x) || is.character(x))]
        })
        output$var_list <- renderUI({
            cat_names <- get_cat_names()
            quan_names <- get_quan_names()
            n_of_cats <- length(cat_names)
            n_of_quans <- length(quan_names)
            if (n_of_cats > 0) {
                div1 <- div(
                    p(paste("因子/字符变量 (", n_of_cats, "个)")),
                    hr(),
                    p(paste(cat_names, collapse = ", ")),
                )
            } else {
                div1 <- div()
            }
            if (n_of_quans > 0) {
                div2 <- div(
                    hr(),
                    p(paste("数值变量 (", n_of_quans, "个)")),
                    hr(),
                    p(paste(quan_names, collapse = ", ")),
                )
            } else {
                div2 <- div()
            }
            list(div1, div2)
        })
        observeEvent(rv$data, {
            updateSelectInput(session, "c_vars", choices = names(rv$data))
            updateSelectInput(session, "q_vars", choices = names(rv$data))
        })
        # 更新变量类型
        observeEvent(input$btn_update, {
            if (length(input$q_vars) == 0 & length(input$c_vars) == 0) {
                showNotification("请至少选择一个变量", type = "error")
            } else {
                if (length(input$q_vars) > 0) {
                    # print(class(input$q_vars))
                    rv$data <- rv$data %>% mutate(across(input$q_vars, as.numeric))
                    showNotification(paste(paste(input$q_vars, collapse = ","), "已更新为数值变量"), type = "message")
                }
                if (length(input$c_vars) > 0) {
                    rv$data <- rv$data %>% mutate(across(input$c_vars, as.character))
                    showNotification(paste(paste(input$c_vars, collapse = ","), "已更新为因子变量"), type = "message")
                }
            }
        })
        # 显示数据预览
        output$data_preview <- renderDT({
            rv$data
        })

        # 显示缺失情况
        output$data_missing <- renderPlot({
            library(reshape2)
            if (!is.null(rv$data)) {
                missing_data <- is.na(rv$data)
                missing_data_melted <- melt(missing_data)
                ggplot(missing_data_melted, aes(x = Var1, y = Var2)) +
                    geom_tile(aes(fill = value), color = "white") +
                    scale_fill_manual(values = c("TRUE" = "red", "FALSE" = "#cfd6cf")) +
                    theme_minimal() +
                    labs(title = "Missing Data Heatmap", x = "Rows", y = "Columns")
            }
        })

        # 显示数据分布
        observeEvent(rv$data, {
            updateSelectInput(session, "var_select", label = "选择要查询的变量", choices = names(rv$data))
        })
        output$data_summary <- renderUI({
            req(input$var_select)
            x <- rv$data[[input$var_select]]
            if (is.numeric(x) && uniqueN(x) > 10) {
                mean_value <- mean(x, na.rm = T)
                std_value <- sd(x, na.rm = T)
                median_value <- quantile(x, probs = 0.50, na.rm = T)
                p25_value <- quantile(x, probs = 0.50, na.rm = T)
                p75_value <- quantile(x, probs = 0.50, na.rm = T)
                max_value <- max(x, na.rm = T)
                min_value <- min(x, na.rm = T)
                div(
                    h6("数据概况:"),
                    hr(),
                    p(paste("Min:", min_value)),
                    p(paste("p25:", p25_value)),
                    p(paste("p50:", median_value)),
                    p(paste("p75:", p75_value)),
                    p(paste("Max:", max_value)),
                    p(paste("Mean:", mean_value)),
                    p(paste("STD:", std_value)),
                    hr(),
                )
            } else {
                div(
                    input$var_select, "数据分布见下图:",
                    hr()
                )
            }
        })
        output$data_dist <- renderPlotly({
            req(input$var_select)
            x <- rv$data[[input$var_select]]
            #   & data.table::uniqueN(x)>10
            if (is.numeric(x) && uniqueN(x) > 10) {
                p1 <- ggplot(data = NULL, aes(x = x)) +
                    geom_density(fill = "steelblue", alpha = 0.5) +
                    ylab("Density") +
                    xlab(input$var_select) +
                    theme_minimal()
                ggplotly(p1)
            } else {
                freq <- as.data.frame(table(rv$data[[input$var_select]]))
                p2 <- plot_ly(
                    data = freq,
                    labels = ~Var1,
                    values = ~Freq,
                    type = "pie",
                    textinfo = "label+percent",
                    insidetextorientation = "radial"
                )
                p2
            }
        })
    })
}
